//
//  WSJPickAndCustomSegment.m
//  testTab
//
//  Created by wsj2015 on 16/3/29.
//  Copyright © 2016年 yz. All rights reserved.
//

#import "WSJPickAndCustomSegment.h"
#import "UIView+SDAutoLayout.h"
#import "WSJPickAndCustomSegment.h"
#import "WSJPickAndCustomCell.h"

#define kMaxLength 10

@interface WSJPickAndCustomSegment ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,  strong) UITableView *tableView;


@property (nonatomic,  assign) NSInteger selectItem;
@property (nonatomic,  strong) NSMutableArray *dataArray;

@end

@implementation WSJPickAndCustomSegment
{
    UIView *backgroundView;
    UIView *chooseView;
    UIView *addView;
    UITableView *tab;
    NSMutableArray *array;
    NSMutableArray *chooseArray;
    UITextField *addText;
    BOOL tapView;
    UILabel *alert;

}
- (UITableView *)tableView{
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        //    tab.backgroundColor = [UIColor redColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        self.tableView.backgroundColor = [UIColor whiteColor];
       
    }
    return _tableView;
}
- (void)setDataSourceArray:(NSArray *)dataSourceArray{
    _dataSourceArray = dataSourceArray;
    if (!dataSourceArray ||dataSourceArray.count==0) {
        return;
    }
    self.dataArray =[NSMutableArray arrayWithArray:dataSourceArray];
    [self.tableView reloadData];
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.selectItem = -1;
        
    }
    return self;
}

- (void)dealloc{
  
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    backgroundView = [[UIView alloc]initWithFrame:self.view.bounds];
    backgroundView.backgroundColor = [UIColor whiteColor];
    [UIView animateWithDuration:0.2 animations:^{
        backgroundView.backgroundColor = [UIColor colorWithRed:157.0/255.0 green:157.0/255.0 blue:157.0/255.0 alpha:1];
    }];
    tapView = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(disappearView:)];
    [backgroundView addGestureRecognizer:tap];
    [self.view addSubview:backgroundView];
    
    chooseView = [[UIView alloc]initWithFrame:CGRectMake(20,100, self.view.bounds.size.width-40, 200)];
    chooseView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:chooseView];
    
    
    UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(15, 15, 100, 15)];
    if (_choosetitle) {
        lab.text = _choosetitle;
    }else {
    
        lab.text = @"PICC类型选择";
    }
    lab.textColor = [UIColor colorWithRed:120/255.0 green:120/255.0 blue:120/255.0 alpha:1];
    lab.tag = 10010;
    lab.font = [UIFont systemFontOfSize:12];
    [chooseView addSubview:lab];
    
    UIButton *addBt = [UIButton buttonWithType:UIButtonTypeCustom];
    
    addBt.frame = CGRectMake(35, lab.bottom+10, 150, 30) ;
    [addBt setImage:[UIImage imageNamed:@"evaluation_add"] forState:UIControlStateNormal];
    [addBt setTitle:@"自定义类型" forState:UIControlStateNormal];
    addBt.titleLabel.font = [UIFont systemFontOfSize:14];
    [addBt setTitleColor:[UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1] forState:UIControlStateNormal];
    addBt.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 50);
    addBt.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 40);
    [addBt addTarget:self action:@selector(add:) forControlEvents:UIControlEventTouchUpInside];
    if (self.type == 1) {
        self.tableView.frame =CGRectMake(0, 70 - 40, chooseView.bounds.size.width, 200 -35-70 + 40);
    }else{
    
        [chooseView addSubview:addBt];
        self.tableView.frame =CGRectMake(0, 70, chooseView.bounds.size.width, 200 -35-70);
    }
    
    
    UIButton *bt1 = [UIButton buttonWithType:UIButtonTypeSystem];
    bt1.frame = CGRectMake(chooseView.width-65, chooseView.height-35, 60, 30);
//    [bt1 setTitleColor:[UIColor colorWithRed:24/255.0 green:180/255.0 blue:237/255.0 alpha:1] forState:UIControlStateNormal];
    bt1.enabled = NO;
    [bt1 setTitle:@"确定" forState:UIControlStateNormal];
    bt1.titleLabel.font = [UIFont systemFontOfSize:16];
    [bt1 addTarget:self action:@selector(bt1:) forControlEvents:UIControlEventTouchUpInside];
    [chooseView addSubview:bt1];
    bt1.tag = 201;
    
    UIButton *bt2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    bt2.frame = CGRectMake(chooseView.width-130, chooseView.height-35, 60, 30);
    
    [bt2 setTitle:@"取消" forState:UIControlStateNormal];
    bt2.titleLabel.font = [UIFont systemFontOfSize:16];
    [bt2 addTarget:self action:@selector(bt2:) forControlEvents:UIControlEventTouchUpInside];
    [chooseView addSubview:bt2];
    
    
    
    
    //    tab.backgroundColor = [UIColor redColor];
    [chooseView addSubview:self.tableView];
    
}


- (void)disappearView:(UITapGestureRecognizer *)tap{
    
    if (tap.view ==chooseView) {
        tap.cancelsTouchesInView = NO;
        return;
    }
    
    if (tapView == YES) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
       
    }else
    {
       
        [addText resignFirstResponder];
    }
    
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"%i",self.dataArray.count);
    return self.dataArray.count;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.selectItem = indexPath.row;
     UIButton *btn =[chooseView viewWithTag:201];
    btn.enabled = YES;
    [self.tableView reloadData];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 39;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    WSJPickAndCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellId"];
    if (cell == nil) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"WSJPickAndCustomCell" owner:nil options:0].lastObject;
    }
    cell.desLabel.text = self.dataArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.selectImageView.image = indexPath.row==self.selectItem?[UIImage imageNamed:@"evaluation_selected"]:[UIImage imageNamed:@"evaluation_unselected"];
    
    
    return cell;
}
-(void)keyboardShow:(NSNotification *)notification
{
    //    backgroundView.userInteractionEnabled = NO;
    CGRect keyBoardFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSLog(@"%f",keyBoardFrame.size.height);
    [UIView animateWithDuration:0.2 animations:^{
        addView.frame = CGRectMake(20, self.view.bounds.size.height-keyBoardFrame.size.height-130, self.view.width-40, 120);
    }];
    
}

-(void)keyboardHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.2 animations:^{
        addView.frame = CGRectMake(20, (self.view.height-120)/2, self.view.width-40, 120);
    }];
}


-(void)add:(id)sender
{
    tapView = NO;
    [chooseView removeFromSuperview];
    addView = [[UIView alloc]initWithFrame:CGRectMake(20, (self.view.height-120)/2, self.view.width-40, 120)];
    addView.backgroundColor = [UIColor whiteColor];
    addView.layer.cornerRadius = 5;
    [backgroundView addSubview:addView];
    
    addText = [[UITextField alloc]initWithFrame:CGRectMake(15, 20, addView.width-30, 40)];
    addText.layer.borderColor = [UIColor colorWithRed:198/255.0 green:198/255.0 blue:198/255.0 alpha:1].CGColor;
    addText.layer.borderWidth = 1;
    addText.font = [UIFont systemFontOfSize:14];
    addText.placeholder = @"请输入其他类...";
    [addText isFirstResponder];
    [addView addSubview:addText];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(change:) name:UITextFieldTextDidChangeNotification object:nil];
    
    UIButton *bt1 = [UIButton buttonWithType:UIButtonTypeSystem];
    bt1.frame = CGRectMake(addView.width-80, addText.bottom+(addView.height-addText.bottom-30)/2, 60, 30);
    [bt1 setTitle:@"确定" forState:UIControlStateNormal];
    bt1.enabled = NO;
    bt1.tag = 301;
    bt1.titleLabel.font = [UIFont systemFontOfSize:16];
    [bt1 addTarget:self action:@selector(backToChooseViewOK) forControlEvents:UIControlEventTouchUpInside];
    [addView addSubview:bt1];
    
    
    UIButton *bt2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    bt2.frame = CGRectMake(addView.width-160, addText.bottom+(addView.height-addText.bottom-30)/2, 60, 30);
    [bt2 setTitle:@"取消" forState:UIControlStateNormal];
    [bt2 setTitleColor:[UIColor colorWithRed:24/255.0 green:180/255.0 blue:237/255.0 alpha:1] forState:UIControlStateNormal];
    bt2.titleLabel.font = [UIFont systemFontOfSize:16];
    [bt2 addTarget:self action:@selector(backToChooseView) forControlEvents:UIControlEventTouchUpInside];
    [addView addSubview:bt2];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];
    
}
-(void)bt1:(UIButton *)bt
{
   
    NSLog(@"确定");
    NSLog(@"%@",chooseArray);
    if (self.callBack) {
        self.callBack(self.dataArray[self.selectItem],self.selectItem);
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
-(void)change:(NSNotification *)ch
{
//    if (addText.text.length >= 10) {
//        addText.text = [addText.text substringToIndex:9];
//    }
    UITextField *textField = addText;
    NSString *toBeString = textField.text;
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > kMaxLength) {
                textField.text = [toBeString substringToIndex:kMaxLength];
            }
        }
        // 有高亮选择的字符串，则暂不对文字进行统计和限制
        else{
            
        }
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else{
        if (toBeString.length > kMaxLength) {
            textField.text = [toBeString substringToIndex:kMaxLength];
        }  
    }
    
    
    
     UIButton *btn =[addView viewWithTag:301];
    if ([addText.text isEqualToString:@""]||!addText.text) {
       
        btn.enabled = NO;
    }else{
        btn.enabled = YES;
    }
    //    lab.text = [NSString stringWithFormat:@"%lu/140字",(unsigned long)_textV.text.length];
}
-(void)bt2:(UIButton *)bt
{
    NSLog(@"取消");
//    [self disappearView];
    [self dismissViewControllerAnimated:YES completion:nil];
//    [array removeAllObjects];
}
-(void)backToChooseViewOK
{
    tapView = YES;
    [self.dataArray addObject:addText.text];
    self.selectItem = self.dataArray.count - 1;
    UIButton *btn =[chooseView viewWithTag:201];
    btn.enabled = YES;
    [self.tableView reloadData];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataArray.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    [addView removeFromSuperview];
    [self.view addSubview:chooseView];
}
-(void)backToChooseView
{
    
    tapView = YES;
    [addView removeFromSuperview];
    [self.view addSubview:chooseView];
}

@end
